# -*- coding: utf-8 -*-
from time import sleep

from config.settings import env
from concurrent.futures import ThreadPoolExecutor, Future, as_completed

import logging

logger = logging.getLogger(__name__)

status: bool = True

executor = ThreadPoolExecutor(max_workers=env.pool_size)


def loop(seconds: int):
    logger.info(f'seconds:{seconds}')
    for i in range(seconds):
        global status
        if status:
            sleep(1)
            pass
        else:
            return i + 1
        pass
    return seconds


def task():
    logger.info('start')
    future_list = list()
    for i in range(1, 5):
        future: Future = executor.submit(loop, i)
        future_list.append(future)
        pass

    # generator = executor.map(loop, list(range(30, 38)), chunksize=2)
    # result_list = [ ]
    # result_list = [future.result() for future in future_list]

    for future in as_completed(future_list):
        result = future.result()
        logger.info(f'result:{result}')
        if result == 2:
            global status
            status = False
            break
        pass
    pass

    max_result = 10
    # max_result = max(result_list)
    # max_result = max(list(generator))
    logger.info(f'stop')
    return max_result


def task1(start_date=None, end_date=None, ):
    logger.info('start')
    future_list = list()
    for i in range(1, 5):
        future: Future = executor.submit(loop, i)
        future_list.append(future)
        pass

    for future in as_completed(future_list):
        result = future.result()
        logger.info(f'result:{result}')
        pass

    max_result = 10
    logger.info(f'stop')
    return max_result


def function(start_date=None, end_date=None, *args, **kwargs):
    logger.info(f'start_date={start_date},end_date={end_date}.')
    future_list = list()
    with ThreadPoolExecutor(max_workers=env.pool_size) as executor:
        for i in range(env.pool_size):
            future: Future = executor.submit(task, )
            future_list.append(future)
            pass
        pass
    result_list = [future.result() for future in future_list]
    logger.info(result_list)
    pass


async def coroutine(start_date=None, end_date=None, *args, **kwargs):
    logger.info(f'start_date={start_date},end_date={end_date}.')
    function(start_date, end_date, *args, **kwargs)
    pass


def task_sleep():
    logger.info('start')
    sleep(60)
    logger.info('stop')

if __name__ == '__main__':
    # function()

    result = task()
    logger.info(f'result:{result}')

    pass
